package org.chen.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.chen.mapper.ArticleRepository;
import org.chen.domain.CrawlerTask;
import org.chen.processor.ESPNPageProcessor;
import org.chen.service.base.BaseWebMagicCrawlerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ESPNCrawlerServiceImpl extends BaseWebMagicCrawlerService {
    
    private final Map<String, String> categoryUrls = new HashMap<>() {{
        put("soccer", "https://www.espn.com/soccer/");
        put("basketball", "https://www.espn.com/basketball/");
        put("rugby", "https://www.espn.com/rugby/");
        put("betting", "https://www.espn.com/sports-betting/");
        put("nba", "https://www.espn.com/nba/");
        put("transfers", "https://www.espn.com/soccer/transfers-news-and-features/");
    }};

    @Value("${crawler.sites.espn.enabled}")
    private boolean enabled;

    public ESPNCrawlerServiceImpl(ArticleRepository articleRepository) {
        super(articleRepository);
    }


    @Override
    protected PageProcessor getPageProcessor(CrawlerTask task) {
        // 根据task中的category获取对应的URL
        String category = task.getCategory();
        String startUrl = categoryUrls.getOrDefault(category, categoryUrls.get("soccer"));

        task.setStartUrl(startUrl);

        log.info("Starting crawler for category: {} with URL: {}", category, startUrl);

        return new ESPNPageProcessor(task);
    }

    @Override
    public String getSourceName() {
        return "espn";
    }

    @Override
    public boolean isSourceAvailable() {
        return enabled;
    }
}